<template>
  <div>
    <div class="mb-1">
      <el-button
        type="primary"
        size="small"
        class="btn-long"
        @click="handleEdit()"
        icon="el-icon-plus"
      >
        留置协议
      </el-button>
    </div>
    <c-table border class="table-sm flex-1" :columns="tableColumns" :data="tableData"></c-table>
    <c-form-dialog
      ref="form"
      :form-data="editData"
      :form-items="formItems"
      :table-id="editId"
      :table-name="tableName"
      :visible.sync="editVisible"
      :before-save="handleBeforeSave"
      @success="getData()"
    ></c-form-dialog>

    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :visible.sync="contractView"
    >
      <pdf-view :contractId="contractId" :view-mode="true" :query-id="queryId"></pdf-view>
    </el-dialog>
  </div>
</template>

<script>
import { idCardValidate, licenseValidate, nzhToMoney } from '@vimi/utils-tool'
import contractGuardMixins from './contractGuardMixins'
import { mapGetters } from 'vuex'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import { phoneValidator } from '@/common/plugins/validator'
import { getIdCard, getOrgInfo } from '@/credit/views/city/program/ocr/index'
const enumEntityType = {
  1: '法人',
  2: '自然人',
}
export default {
  components: {
    PdfView,
  },
  props: {
    tableData: {
      type: Array,
      default: () => [],
    },
    queryId: String,
    relatedData: {
      type: Object,
      default: () => ({}),
    },
  },
  mixins: [contractGuardMixins],
  data() {
    const certNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (+this.entityType === 1 && !licenseValidate(value)) {
        callback(new Error('错误的营业执照号，请重新输入'))
      } else if (+this.entityType !== 1 && !idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      enumEntityType,
      postData: {},
      saveLoading: false,
      tableName: 'gua_contract',
      editVisible: false,
      editId: '',
      tableColumns: [
        {
          attrs: { label: '留置主体类型', prop: 'gua_entity_type', align: 'center' },
          process: v => enumEntityType[v],
        },
        { attrs: { label: '留置主体', prop: 'gua_entity', align: 'center' } },
        { attrs: { label: '法人名称', prop: 'gua_entity_corp', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'gua_entity_mobile', align: 'center' } },
        { attrs: { label: '居民身份证/营业执照号', prop: 'gua_entity_cert_no', align: 'center' } },
        { attrs: { label: '留置清单', prop: 'gua_list_des', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center' },
          operations: [
            {
              content: '查看',
              icon: 'fa fa-search',
              attrs: { class: 'p-0 mx-1' },
              event: this.handleView,
            },
            {
              content: '编辑',
              icon: 'fa fa-edit',
              attrs: { class: 'text-info p-0 mx-2' },
              event: this.handleEdit,
              ifRender: row => +row.sign_status === 0,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger p-0 m-1' },
              event: this.deleteRow,
              ifRender: row => +row.sign_status === 0,
            },
          ],
        },
      ],
      formItems: [
        {
          tag: 'c-select',
          itemAttrs: {
            label: '留置主体类型',
            rules: [{ required: true, message: '请选择留置主体类型', trigger: 'change' }],
          },
          attrs: {
            key: 'gua_entity_type',
            value: '',
            class: 'form-control-ml',
            placeholder: '请选择留置主体类型',
            options: enumEntityType,
          },
          listeners: {
            change: v => {
              this.entityType = v
            },
          },
        },
        {
          tag: 'upload',
          itemAttrs: { label: '身份证头像页OCR识别(非必填)' },
          attrs: {
            key: 'cert_attachment',
            singleImage: true,
            dir: `credit/contract/pledge/funds/${this.queryId}`,
            'on-change': this.registerChange,
          },
          getItemAttrs: model => {
            return {
              label:
                +model.gua_entity_type === 1
                  ? '营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)(非必填)'
                  : '身份证头像页OCR识别(非必填)',
            }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '留置主体',
            rules: [{ required: true, message: '请输入留置主体', trigger: 'blur' }],
          },
          attrs: { key: 'gua_entity', value: '', placeholder: '请输入留置主体' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '法人名称',
            rules: [{ required: true, message: '请输入留置主体法人名称', trigger: 'blur' }],
          },
          attrs: { key: 'gua_entity_corp', value: '', placeholder: '请输入留置主体法人名称' },
          ifRender: model => +model.gua_entity_type === 1,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入联系电话', trigger: 'blur' },
              { validator: phoneValidator, message: '请输入正确的电话号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'gua_entity_mobile', value: '' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '居民身份证/营业执照号',
            rules: [
              { required: true, message: '请输入居民身份证/营业执照号', trigger: 'blur' },
              { validator: certNoValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'gua_entity_cert_no', value: '' },
        },
        {
          tag: 'textarea',
          itemAttrs: {
            label: '留置清单',
            rules: [{ required: true, message: '请输入留置清单', trigger: 'blur' }],
          },
          attrs: { key: 'gua_list_des', value: '', autosize: { minRows: 3 } },
        },
      ],
      editData: {},
      entityType: 2,
      contractView: false,
      contractId: '',
      ocrFile: '',
    }
  },
  computed: {
    ...mapGetters(['entrustContract']),
    isView() {
      return +this.entrustContract.sign_status > 0
    },
    isCommon() {
      return +this.entityType === 1
    },
  },
  created() {},
  methods: {
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      this.ocrFile = file.raw
      this.loading = true
      if (this.isCommon) {
        getOrgInfo(this.ocrFile)
          .then(res => {
            const data = res?.data ?? {}
            this.$refs.form.setAttrs('gua_entity', { value: data.name || '' })
            this.$refs.form.setAttrs('gua_entity_cert_no', { value: data.reg_num || '' })
            this.$refs.form.setAttrs('gua_entity_corp', { value: data.person || '' })
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        getIdCard(this.ocrFile, true)
          .then(res => {
            const data = res?.data ?? {}
            this.$refs.form.setAttrs('gua_entity', { value: data.name || '' })
            this.$refs.form.setAttrs('gua_entity_cert_no', { value: data.num || '' })
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    handleBeforeSave(model) {
      model.customer_related_id = this.queryId
      model.customer_name = this.relatedData.customer_name
      model.customer_address = this.relatedData.address
      model.customer_phone = this.relatedData.mobile_no
      model.bank_name = this.entrustContract.bank_name
      model.apply_funds = this.entrustContract.reply_funds
      model.apply_funds_capital = nzhToMoney(this.entrustContract.reply_funds * 10000)
      model.loan_contract_no = this.entrustContract.loan_contract_no
      model.ensure_contract_no = this.entrustContract.ensure_contract_no
      model.gua_com_corp = this.entrustContract.accept_entrust_entity_corp
      model.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      model.gua_method = 4
      const num = this.tableData.reduce((x, y) => (x > +y.order_num ? x : +y.order_num), 0)
      model.order_num = num + 1
      return model
    },
    handleView(p) {
      this.contractId = p.doc_id || ''
      this.contractView = true
    },
    beforeClose() {
      this.contractView = false
    },
    handleEdit(row = {}) {
      this.editId = row.gua_contract_id || ''
      this.entityType = row.gua_entity_type || 2
      this.editData = { ...row, gua_entity_type: row.gua_entity_type || '2' }
      this.editVisible = true
    },
    getData() {
      this.$store.dispatch('getGuardsData', this.queryId)
    },
    deleteRow(row) {
      const id = row.gua_contract_id
      this.$utils
        .msgbox({
          message: `确定删除合同?`,
          beforeClose: () => this.deleteData(id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.$store.dispatch('getGuardsData', this.queryId)
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.item-contract {
  min-width: 600px;
}
</style>
